import { changeCartNum, deleteCart, getCartList } from '@/api/cart'
import { Toast } from 'vant'

export default {
  namespaced: true,
  state: {
    cartList: []
  },
  getters: {
    // 所有总数
    cartTotal (state) {
      return state.cartList.reduce((total, item) => {
        return total + item.goods_num
      }, 0)
    },
    // 选中的列表
    selCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    // 选中的总数
    selTotalNum (state, getters) {
      return getters.selCartList.reduce((total, item) => {
        return total + item.goods_num
      }, 0)
    },
    // 选中的总价格
    selTotalPrice (state, getters) {
      return getters.selCartList.reduce((total, item) => {
        return total + item.goods_num * item.goods.goods_price_min
      }, 0).toFixed(2)
    },
    isAllChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  },
  mutations: {
    addCart (state, obj) {
      state.cartList.push(obj)
    },
    removeCart (state, obj) {
      state.cartList.splice(obj, 1)
    },
    setCartList (state, obj) {
      state.cartList = obj
    },
    toggleCheck (state, id) {
      const goods = state.cartList.find(item => item.goods_id === id)
      goods.isChecked = !goods.isChecked
    },
    toggleAllCheck (state, flag) {
      state.cartList.forEach(item => {
        item.isChecked = flag
      })
    },
    changeCount (state, obj) {
      const { id, value } = obj
      state.cartList.find(item => item.goods_id === id).goods_num = value
    }
  },
  actions: {
    async getcartList (context) {
      const { data: { list } } = await getCartList()

      // 默认选中
      list.forEach(element => {
        element.isChecked = true
      })

      context.commit('setCartList', list)
      console.log(list)
    },
    async changeCount (context, obj) {
      const { goodsId, goodsNum, goodsSkuId } = obj
      await changeCartNum(goodsId, goodsNum, goodsSkuId)
    },
    async deleteCart (context) {
      const ids = context.state.cartList.filter(item => item.isChecked).map(item => {
        return item.id
      })
      await deleteCart(ids)

      context.dispatch('getcartList')
      Toast('删除成功')
    }
  }
}
